<?php
// $Id$

/**
 * Controller_Search 控制器
 *
 * 搜东西，利用本地数据库而非Google
 *
 * DisallowSeach : app_store
 * DisallowSeach : course
 * DisallowSeach : login
 * DisallowSeach : major
 * DisallowSeach : slogin
 * DisallowSeach : tdoc
 * DisallowSeach : teacher_course
 * DisallowSeach : teacher_title
 * DisallowSeach : t_browser_by_date
 * DisallowSeach : t_unknown)browser_by_date
 * DisallowSeach : t_ip_by_date
 * DisallowSeach : t_uri_by_date
 * DisallowSeach : t_referer_by_date
 * DisallowSeach : t_hit_by_date
 * DisallowSeach : t_hour
 * AllowSeach : file                   -- 文件下载系统
 * AllowSeach : file_ctgry             -- 文件下载系统
 * AllowSeach : {news} -- 视图或数据表 -- 新闻管理系统
 * AllowSeach : news_attachment        -- 新闻管理系统
 * AllowSeach : news_ctgry             -- 新闻管理系统
 * AllowSeach : tag                    -- 新闻管理系统
 * AllowSeach : teacher                -- 教师管理系统
 * AllowSeach : title                  -- 教师管理系统
 *
 * 结果要求高亮关键字
 */
class Controller_Search extends Controller_Abstract
{

    public function actionIndex()
    {
        $q      = $_GET['q'];
        $subsys = isset($_GET['subsys']) ? $_GET['subsys'] : 'all';
        $spec   = isset($_GET['spec'])   ? $_GET['spec']   : NULL;

        /**
         * 初始化总记录信息
         */
        $counter = 0;
        $fileSys = $newsSys = $teacherSys = array('counter'=>0);
        $resultSetRegistry = array();

        /**
         * Errot handling 不符合要求的关键字直接跳转
         */
        if(!CIB::_SQL_filter($q))
        {
            return $this->_redirect(url('home/index'));
        }

        // 生产 resultNavigator 片断代码
        /**
         * 文件管理系统计数器
         */
        $fileSys['fileCount']      = File::find('filename like ?', '%'.$q.'%')->getCount();
        $fileSys['fileCtgryCount'] = FileCategory::find('category like ?', '%'.$q.'%')->getCount();
        $fileSys['counter'] = array_sum($fileSys);

        /**
         * 新闻管理系统计数器
         */
        $newsSys['newsTitleCount']      = News::find('title like ?', '%'.$q.'%')->getCount();
        $newsSys['newsBodyCount']       = News::find('body like ?', '%'.$q.'%')->getCount();
        $newsSys['newsAttachmentCount'] = NewsAttachment::find('filename like ?', '%'.$q.'%')->getCount();
        $newsSys['newsCtgryCount']      = NewsCategory::find('category like ?', '%'.$q.'%')->getCount();
        $newsSys['tagCount']            = Tag::find('tag like ?', '%'.$q.'%')->getCount();
        $newsSys['counter'] = array_sum($newsSys);

        /**
         * 教师管理系统计数器
         */
        $teacherSys['nameCount']        = Teacher::find('name like ?', '%'.$q.'%')->getCount();
        $teacherSys['descriptionCount'] = Teacher::find('description like ?', '%'.$q.'%')->getCount();
        $teacherSys['titleCount']       = Title::find('title like ?', '%'.$q.'%')->getCount();
        $teacherSys['contactCount']     = Teacher::find('email like ?', '%'.$q.'%')->orWhere('fax like ?', '%'.$q.'%')->orWhere('phone like ?', '%'.$q.'%')->getCount();
        $teacherSys['counter'] = array_sum($teacherSys);

        /* 总计数器 */
        $counter = $fileSys['counter'] + $newsSys['counter'] + $teacherSys['counter'];

        $this->_view['counter'] = $counter;
        $this->_view['fileSys'] = $fileSys;
        $this->_view['newsSys'] = $newsSys;
        $this->_view['teacherSys'] = $teacherSys;

        $searchIn = array('newsSys'=>'on', 'teacherSys'=>'on', 'fileSys'=>'on');


        switch($subsys)
        {
            case 'all' :
                /** 表示首页，准备符合要求的显示数据，1-3条新闻，1-7条老师，1-3个文件
                 * 顺序:先找 title 符合的，达到3条后停止
                 * 找 body 符合的，达到3条后停止
                 * 链接先不管
                 */
                # 新闻片断
                $newsCountFlag = 3;
                $newsByContent = News::find('title like ?', '%'.$q.'%')->all()->order(Q::ini('appini/sort'))->limit(0, $newsCountFlag)->query();

                if(($newsCountLeft = $newsCountFlag - $newsByContent->count()) > 0)
                {
                    $newsByBody = News::find('body like ?', '%'.$q.'%')->all()->order(Q::ini('appini/sort'))->limit(0, $newsCountLeft)->query();
                    $newsByContent->append($newsByBody);
                }

                // 处理newsContent 的 body 部分
                $abbvLength = Q::ini('appini/search_abbv_news_body_length');

                foreach($newsByContent as $n)
                {
                    $pos = mb_strpos(str_replace('&nbsp;', '', strip_tags($n->body)), $q, 0, 'utf-8');
                    if(($stringStart = $pos - $abbvLength) < 0)
                    {
                        $stringStart = 0;
                    }
                    $stringLength = $abbvLength*2;
                    if((mb_strlen($n->body, 'utf-8') - $pos - $stringLength) < 0)
                    {
                        $stringLength = mb_strlen($n->body, 'utf-8') - $pos;
                    }

                    $strLength = mb_strlen($n->body, 'utf-8');
                    $n->body = strip_tags($n->body);
                    $n->body = str_replace('&nbsp;', '', $n->body);
                    $n->body = mb_substr($n->body, $stringStart, $stringLength, 'utf-8');
                    $n->body = str_replace($q, '<span class="highlight">'.$q.'</span>', $n->body);
                    if(strpos($n->title, $q) !== FALSE)
                    {
                        $n->title = str_replace($q, '<span class="highlight">'.$q.'</span>', $n->title);
                    }

                    if($stringStart > 0)
                    {
                        $n->body = '...'.$n->body;
                    }
                    if(($strLength - $pos - $stringLength) > 0)
                    {
                        $n->body .= '...';
                    }
                }

                # 教师片断
                $teacherCountFlag = 1;
                $teacherByName = Teacher::find('name like ?', '%'.$q.'%')->all()->order('teacher_id ASC')->limit(0, $teacherCountFlag)->query();
                if(($teacherCountLeft = $teacherCountFlag - $teacherByName->count()) > 0)
                {
                    $teacherByDescription = Teacher::find('description like ?', '%'.$q.'%')->all()->order('teacher_id ASC')->limit(0, $teacherCountLeft)->query();
                    $teacherByName->append($teacherByDescription);
                }

                foreach($teacherByName as $t)
                {
                    if(strpos($t->name, $q) !== FALSE)
                    {
                        $t->name = str_replace($q, '<span class="highlight">'.$q.'</span>', $t->name);
                    }

                    if(strpos($t->description, $q) !== FALSE)
                    {
                        $t->description = str_replace($q, '<span class="highlight">'.$q.'</span>', strip_tags($t->description));
                    }
                }

                # 文件片断
                $fileCountFlag = 3;
                $fileByFilename = File::find('filename like ?', '%'.$q.'%')->all()->order('created DESC')->limit(0, $fileCountFlag)->query();
                if(($fileCountLeft = $fileCountFlag - $fileByFilename->count()) > 0)
                {
                    $fileByDescription = File::find('description like ?', '%'.$q.'%')->all()->order('created DESC')->limit(0, $fileCountLeft)->query();
                    $fileByFilename->append($fileByDescription);
                }

                foreach($fileByFilename as $f)
                {
                    if(strpos($f->filename, $q) !== FALSE)
                    {
                        $f->filename = str_replace($q, '<span class="highlight">'.$q.'</span>', $f->filename);
                    }

                    if(strpos($f->description, $q) !== FALSE)
                    {
                        $f->description = str_replace($q, '<span class="highlight">'.$q.'</span>', strip_tags($f->description));
                    }

                    if($f->description == NULL || $f->description == '')
                    {
                        $f->description = '<span style="color:#777777">该文件暂无描述</span>';
                    }
                }

                break;

            case 'newsSys' :

                $searchIn['fileSys'] = $searchIn['teacherSys'] = 'off';

                switch($_GET['spec'])
                {
                    case 'title' :
                        $newsByContent = News::find('title like ?', '%'.$q.'%')->order(Q::ini('appini/sort'))->all()->query();
                        break;
                    case 'body' :
                        $newsByContent = News::find('body like ?', '%'.$q.'%')->order(Q::ini('appini/sort'))->all()->query();
                        break;
                }

                // 处理newsContent 的 body 部分
                $abbvLength = Q::ini('appini/search_abbv_news_body_length');

                foreach($newsByContent as $n)
                {
                    $pos = mb_strpos(str_replace('&nbsp;', '', strip_tags($n->body)), $q, 0, 'utf-8');
                    if(($stringStart = $pos - $abbvLength) < 0)
                    {
                        $stringStart = 0;
                    }
                    $stringLength = $abbvLength*2;
                    if((mb_strlen($n->body, 'utf-8') - $pos - $stringLength) < 0)
                    {
                        $stringLength = mb_strlen($n->body, 'utf-8') - $pos;
                    }

                    $strLength = mb_strlen($n->body, 'utf-8');
                    $n->body = strip_tags($n->body);
                    $n->body = str_replace('&nbsp;', '', $n->body);
                    $n->body = mb_substr($n->body, $stringStart, $stringLength, 'utf-8');
                    $n->body = str_replace($q, '<span class="highlight">'.$q.'</span>', $n->body);
                    if(strpos($n->title, $q) !== FALSE)
                    {
                        $n->title = str_replace($q, '<span class="highlight">'.$q.'</span>', $n->title);
                    }

                    if($stringStart > 0)
                    {
                        $n->body = '...'.$n->body;
                    }
                    if(($strLength - $pos - $stringLength) > 0)
                    {
                        $n->body .= '...';
                    }
                }
                break;

            case 'teacherSys' :

                $searchIn['newsSys'] = $searchIn['fileSys'] = 'off';

                switch($_GET['spec'])
                {
                    case 'name' :
                        $teacherByName = Teacher::find('name like ?', '%'.$q.'%')->order('teacher_id ASC')->all()->query();
                        break;
                    case 'description' :
                        $teacherByName = Teacher::find('description like ?', '%'.$q.'%')->order('teacher_id ASC')->all()->query();
                        break;
                }

                // 处理newsContent 的 body 部分
                $abbvLength = Q::ini('appini/search_abbv_teacher_description_length');

                foreach($teacherByName as $t)
                {

                    $pos = mb_strpos(str_replace('&nbsp;', '', strip_tags($t->description)), $q, 0, 'utf-8');
                    if(($stringStart = $pos - $abbvLength) < 0)
                    {
                        $stringStart = 0;
                    }
                    $stringLength = $abbvLength*2;
                    if((mb_strlen($t->description, 'utf-8') - $pos - $stringLength) < 0)
                    {
                        $stringLength = mb_strlen($t->description, 'utf-8') - $pos;
                    }

					//  算法好像不对，$strLength 放第三行
                    $strLength = mb_strlen($t->description, 'utf-8');
                    $t->description = strip_tags($t->description);
                    $t->description = str_replace('&nbsp;', '', $t->description);
                    $t->description = mb_substr($t->description, $stringStart, $stringLength, 'utf-8');
                    $t->description = str_replace($q, '<span class="highlight">'.$q.'</span>', $t->description);
                    if(strpos($t->name, $q) !== FALSE)
                    {
                        $t->name = str_replace($q, '<span class="highlight">'.$q.'</span>', $t->name);
                    }

                    if($stringStart > 0)
                    {
                        $t->description = '...'.$t->description;
                    }
                    if(($strLength - $pos - $stringLength) > 0)
                    {
                        $t->description .= '...';
                    }
                }

                break;

            case 'fileSys' :

                $searchIn['newsSys'] = $searchIn['teacherSys'] = 'off';

                switch($_GET['spec'])
                {
                    case 'filename' :
                        $fileByFilename = File::find('filename like ?', '%'.$q.'%')->order('created DESC')->all()->query();
                        break;
                    case 'description' :
                        $fileByFilename = File::find('description like ?', '%'.$q.'%')->order('created DESC')->all()->query();
                        break;
                }

                foreach($fileByFilename as $f)
                {
                    if(strpos($f->filename, $q) !== FALSE)
                    {
                        $f->filename = str_replace($q, '<span class="highlight">'.$q.'</span>', $f->filename);
                    }

                    if(strpos($f->description, $q) !== FALSE)
                    {
                        $f->description = str_replace($q, '<span class="highlight">'.$q.'</span>', strip_tags($f->description));
                    }

                    if($f->description == NULL || $f->description == '')
                    {
                        $f->description = '<span style="color:#777777">该文件暂无描述</span>';
                    }
                }

                break;

        }

        global $g_boot_time;
        $query_time = round(microtime(true) - $g_boot_time, 2);

        if($searchIn['newsSys'] == 'on')
        {
            $this->_view['newsByContent']  = $newsByContent;
        }
        if($searchIn['teacherSys'] == 'on')
        {
            $this->_view['teacherByName']  = $teacherByName;
        }
        if($searchIn['fileSys'] == 'on')
        {
            $this->_view['fileByFilename'] = $fileByFilename;
        }

        $this->_view['searchIn'] = $searchIn;
        $this->_view['query_time'] = $query_time;
    }
}